package com.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * 数据库工具包
 * @author Administrator
 *
 */
public class DbUtils {

//	public static final String DRIVER_NAME="com.mysql.jdbc.Driver";
//	public static final String URL="jdbc:mysql://127.0.0.1:3306/gupaoedu_db?characterEncoding=UTF-8&rewriteBatchedStatements=true";
//	public static final String USERNAME="root";
//	public static final String PWASSWORD="root";
	public static final String DRIVER_NAME="oracle.jdbc.driver.OracleDriver";
	public static final String URL="jdbc:oracle:thin:@127.0.0.1:1521:XE";
	public static final String USERNAME="enroll_sys";
	public static final String PWASSWORD="enroll";
	
	/**
	 * 在多线程的情况下，每个线程都有自己的独立id
	 */
	public static final ThreadLocal<Connection> connLocal = new ThreadLocal<Connection>();//可以理解为map集合
	
	static {
		//加载驱动
		try {
			Class.forName(DRIVER_NAME);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException("数据库驱动加载失败:"+e.getMessage());
		}
	}
	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConn(){
		Connection conn = connLocal.get();//获取连接，如果连接已存在继续使用，否则创建
		if(conn==null){
			//获取连接
			try {				
				conn = DriverManager.getConnection(URL, USERNAME, PWASSWORD);
			    conn.setAutoCommit(false);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("数据库连接出错:"+e.getMessage());
			}
			connLocal.set(conn);//连接用完之后放到map集合里面去，在这边是取
		}
		return conn;
	}
	
	/**
	 * 数据库连接关闭
	 */
	public static void close(){
		
		Connection conn = connLocal.get();//这样子相当于session，把当前用户id放入session，然后进行操作，退出时，把session置空
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		connLocal.set(null);//有取就有还，在关闭连接这边把连接置空，就算close了，还是有值，会出问题
	}
	
	/**
	 * sql回滚
	 */
	public static void rollback(){
		Connection conn = connLocal.get();
		try {
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * sql提交
	 * @throws SQLException
	 */
	public static void commit() throws SQLException{
		Connection conn = connLocal.get();
		conn.commit();
	}
	
	/**
	 * 获得seqid，通过自增序列号
	 * @param seqName
	 * @return
	 * @throws SQLException		抛出异常好回滚
	 */
	public static Long getSeq(String seqName) throws SQLException{
		Connection conn = connLocal.get();
		Long id = null;
		String sql="select "+seqName+".nextval from dual";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				id = rs.getLong(1);
				break;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return id;
	}
}
